package tasks

import (
	"fmt"
	"github.com/robfig/cron"
	"reflect"
	"runtime"
	"time"
)

// Cron 定时器单例
var Cron *cron.Cron

// Run 运行
func Run(job func() error) {
	from := time.Now().UnixNano()
	err := job()
	to := time.Now().UnixNano()
	jobName := runtime.FuncForPC(reflect.ValueOf(job).Pointer()).Name()
	if err != nil {
		fmt.Printf("%s error: %dms\n", jobName, (to - from)/int64(time.Microsecond))
	} else {
		fmt.Printf("%s success: %dms\n", jobName, (to - from)/int64(time.Microsecond))
	}
}


// CronJob 定时任务
func CronJob() {
	if Cron == nil{
		Cron = cron.New()
	}
	//  0  0  0 * * *
	//Field name   | Mandatory? | Allowed values  | Allowed special characters
	//----------   | ---------- | --------------  | --------------------------
	//Seconds      | Yes        | 0-59            | * / , -
	//Minutes      | Yes        | 0-59            | * / , -
	//Hours        | Yes        | 0-23            | * / , -
	//Day of month | Yes        | 1-31            | * / , - ?
	//Month        | Yes        | 1-12 or JAN-DEC | * / , -
	//Day of week  | Yes        | 0-6 or SUN-SAT  | * / , - ?
	// 在0分0秒0时的时候执行后边的方法
	Cron.AddFunc("0 0 0 * * *", func() { Run(RestartDailyRank)})
	Cron.Start()

	fmt.Println("Cron job start...")
}